﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using BusinessFacade;
using EntityManage;
using System.Text;

public partial class Modules_Personal_PerfApply : System.Web.UI.Page
{
    IPerf_Personal_TargetHandler targetHandler = new Perf_Personal_TargetManage();
    IPerf_Personal_EvaluateHandler evaHandler = new Perf_Personal_EvaluateManage();
    IPerf_Personal_EvaluateDtlHandler evaDtlHandler = new Perf_Personal_EvaluateDtlManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_OrganizationHandlerExt orgExtHandler = new Sys_OrganizationManageExt();
    ISys_PostHandler postHandler = new Sys_PostManage();
    IPerf_Personal_TargetOwnerHandler toHandler = new Perf_Personal_TargetOwnerManage();
    IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();
    IPerf_Personal_ModTargetDtlHandler modTargetDtlHandler = new Perf_Personal_ModTargetDtlManage();
    IPerf_Personal_TargetTypeHandler ttHandler = new Perf_Personal_TargetTypeManage();

    ISys_ConfigHandler configHandler = new Sys_ConfigManage();

    double baseScore = 100;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Id";
            ViewState["Accending"] = "desc";

            RefreshDataGridView();
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("303020"))
            {
                btnCreate.Visible = strPur.Contains("303020");
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    #region dataBind
    /// <summary>
    /// 初始化岗位信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            FillSearchDDL();

            SqlParameter[] parms2 = null;
            int counter = 0;
            DataTable dt = new DataTable();

            if (whereClause != string.Empty)
            {
                dt = evaHandler.GetPerf_Personal_EvaluateByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                whereClause = "1=1";
                ProcessParms(ref whereClause, ref parms2);
                counter = evaHandler.GetCounter(whereClause, parms2);
            }
            else
            {
                dt = evaHandler.GetPerf_Personal_EvaluateByPageList(ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                counter = evaHandler.GetCounter();
            }

            this.AspNetPager.RecordCount = counter;
            gvEvaluateList.DataSource = dt;
            gvEvaluateList.DataBind();
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        // 读取本单位
        int userId = int.Parse(Session["CurrentUserID"].ToString());
        Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(userId);
        int orgId = userQuery.Org_ID;
        
        // 将该单位下该岗位的人查出来
        string orgIds = orgExtHandler.GetAllChildIdsByParentID(orgId);

        //如果是所长室的用户 就把同级部门的人查出来
        string sameLevlOrgIDs = string.Empty;

        Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(orgId);
        if (orgQuery != null)
        {
            if (orgQuery.Name == "所长室")
            {
                Sys_OrganizationQuery[] orgQuerys = orgHandler.GetSys_OrganizationQueryList("Parent_ID=@Parent_ID and Status=1", new SqlParameter[] { new SqlParameter("@Parent_ID",orgQuery.Parent_ID) });
                if (orgQuerys != null && orgQuerys.Length > 0)
                {
                    foreach (Sys_OrganizationQuery q in orgQuerys)
                    {
                        sameLevlOrgIDs += q.ID + ",";
                    }
                }
            }
        }

        orgIds = (orgIds.Length > 0 ? orgIds + "," + orgId : orgId.ToString());
        if(sameLevlOrgIDs.TrimEnd(new char[]{','}).Length>0)
        {
            orgIds = orgIds + "," + sameLevlOrgIDs.TrimEnd(new char[] { ',' }); 
        }
        Sys_UserQuery[] userList = userHandler.GetSys_UserQueryList(" (Org_ID in (" + orgIds + ") or Org_ID2 in (" + orgIds + ")) and Status = @Status and Name like '%' + @Name + '%'"
            , new SqlParameter[] { new SqlParameter("@Status", (int)Enums.NormalStatus.Vallid), new SqlParameter("@Name", txtTargetUserName.Text.Trim())});
        List<string> orgIdList = new List<string>();
        orgIdList.AddRange(orgIds.Split(','));
        StringBuilder userIds = new StringBuilder();
        if (userList != null && userList.Length > 0)
        {
            foreach (Sys_UserQuery user in userList)
            {
                int userOrgId = (user.Org_ID2 != 0 ? user.Org_ID2 : user.Org_ID);

                if (orgIdList.Contains(userOrgId.ToString()))
                {
                    userIds.Append(user.ID);
                    userIds.Append(",");
                }
            }
            userIds = userIds.Remove(userIds.Length - 1, 1);
        }

        whereClause += " and Target_User_ID in (" + userIds.ToString() + ")";

        if (ViewState["SearchTOID"] != null)
        {
            whereClause += " and TargetOwner_ID = @TargetOwner_ID";
            lstParm.Add(new SqlParameter("@TargetOwner_ID", int.Parse(ViewState["SearchTOID"].ToString())));
        }

        //绩效呈批什么状态都可以呈批
        //if (ViewState["SearchStatus"] != null)
        //{
        //    whereClause += " and Status = @Status";
        //    lstParm.Add(new SqlParameter("@Status", int.Parse(ViewState["SearchStatus"].ToString())));
        //}

        parms = lstParm.ToArray();
    }

    private void FillSearchDDL()
    {
        FillSearchTO();
        FillSearchStatus();
    }

    private void FillSearchTO()
    {
        DataTable dt = toHandler.GetPerf_Personal_TargetOwnerList();
        ddlSearchTo.DataTextField = "Name";
        ddlSearchTo.DataValueField = "ID";
        ddlSearchTo.DataSource = dt;
        ddlSearchTo.DataBind();
        ddlSearchTo.Items.Insert(0, new ListItem("全部....", "0"));
    }

    private void FillSearchStatus()
    {
        //DataTable dtStatus = new DataTable();
        //dtStatus.Columns.Add("Value");
        //dtStatus.Columns.Add("Name");
        //DataRow drStatus;

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = "-1";
        //drStatus[1] = "全部....";
        //dtStatus.Rows.Add(drStatus);

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = (int)Enums.PersonalEvaluateStatus.NewAdded;
        //drStatus[1] = Enums.GetPersonalEvaluateStatus(Enums.PersonalEvaluateStatus.NewAdded);
        //dtStatus.Rows.Add(drStatus);

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = (int)Enums.PersonalEvaluateStatus.Apply;
        //drStatus[1] = Enums.GetPersonalEvaluateStatus(Enums.PersonalEvaluateStatus.Apply);
        //dtStatus.Rows.Add(drStatus);

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = (int)Enums.PersonalEvaluateStatus.Passed;
        //drStatus[1] = Enums.GetPersonalEvaluateStatus(Enums.PersonalEvaluateStatus.Passed);
        //dtStatus.Rows.Add(drStatus);

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = (int)Enums.PersonalEvaluateStatus.Notice;
        //drStatus[1] = Enums.GetPersonalEvaluateStatus(Enums.PersonalEvaluateStatus.Notice);
        //dtStatus.Rows.Add(drStatus);

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = (int)Enums.PersonalEvaluateStatus.Archive;
        //drStatus[1] = Enums.GetPersonalEvaluateStatus(Enums.PersonalEvaluateStatus.Archive);
        //dtStatus.Rows.Add(drStatus);

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = (int)Enums.PersonalEvaluateStatus.NotPassed;
        //drStatus[1] = Enums.GetPersonalEvaluateStatus(Enums.PersonalEvaluateStatus.NotPassed);
        //dtStatus.Rows.Add(drStatus);

        //drStatus = dtStatus.NewRow();
        //drStatus[0] = (int)Enums.PersonalEvaluateStatus.Invalid;
        //drStatus[1] = Enums.GetPersonalEvaluateStatus(Enums.PersonalEvaluateStatus.Invalid);
        //dtStatus.Rows.Add(drStatus);

        //ddlSearchStatus.DataSource = dtStatus;
        //ddlSearchStatus.DataTextField = "Name";
        //ddlSearchStatus.DataValueField = "Value";
        //ddlSearchStatus.DataBind();
    }
    #endregion

    #region gvEvaluateList

    protected void gvEvaluateList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //
        if (e.CommandName == "view")
        {
            
        }
    }

    protected void gvEvaluateList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Sys_ConfigQuery ConfigQuery = configHandler.GetSys_ConfigQuery(1);
            if (ConfigQuery != null)
            {
               double.TryParse( ConfigQuery.ConfigValue,out baseScore);
            }


            //绩效呈批什么状态都可以呈批
            if (e.Row.RowIndex > -1)
            {
                //HtmlInputCheckBox chkSelected = (HtmlInputCheckBox)e.Row.FindControl("chkSelected");
                //if (int.Parse(e.Row.Cells[7].Text.Trim()) == (int)Enums.PersonalEvaluateStatus.NewAdded)
                //    chkSelected.Visible = true;
                //else
                //    chkSelected.Visible = false;

                Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[2].Text));
                if (userQuery != null)
                    e.Row.Cells[2].Text = userQuery.Name;
                else
                    e.Row.Cells[2].Text = string.Empty;

                userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[3].Text));
                if (userQuery != null)
                    e.Row.Cells[3].Text = userQuery.Name;
                else
                    e.Row.Cells[3].Text = string.Empty;

                Perf_Personal_TargetOwnerQuery toQuery = toHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(e.Row.Cells[4].Text));
                if (toQuery != null)
                    e.Row.Cells[4].Text = toQuery.Name;
                else
                    e.Row.Cells[4].Text = string.Empty;
                //Enums.PersonalEvaluateStatus status = (Enums.PersonalEvaluateStatus)int.Parse(e.Row.Cells[7].Text);
                //e.Row.Cells[7].Text = Enums.GetPersonalEvaluateStatus(status);

                int id = int.Parse(e.Row.Cells[5].Text);
                e.Row.Cells[5].Text = "";
                Perf_Personal_EvaluateQuery query = evaHandler.GetPerf_Personal_EvaluateQuery(id);
                if (query != null)
                {
                    double totalScore = 0;
                    Perf_Personal_EvaluateDtlQuery[] dtlQueryList = evaDtlHandler.GetPerf_Personal_EvaluateDtlQueryList("Evaluate_ID = @Evaluate_ID", new SqlParameter[]{new SqlParameter("@Evaluate_ID", query.ID)});
                    if (dtlQueryList != null && dtlQueryList.Length > 0)
                    {
                        foreach (Perf_Personal_EvaluateDtlQuery dtlQuery in dtlQueryList)
                        {
                            Perf_Personal_TargetQuery targetQuery = targetHandler.GetPerf_Personal_TargetQuery(dtlQuery.Target_ID);
                            if (targetQuery != null)
                                totalScore = totalScore + (dtlQuery.Score);
                        }
                    }
                    e.Row.Cells[5].Text = (baseScore + totalScore).ToString();
                }

            }
        }
    }

    protected void gvEvaluateList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshDataGridView();
    }

    #endregion

    #region Button

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (!ddlSearchTo.SelectedValue.Equals("0"))
            ViewState["SearchTOID"] = ddlSearchTo.SelectedValue;
        else
            ViewState["SearchTOID"] = null;

        //if (!ddlSearchStatus.SelectedValue.Equals("-1"))
        //    ViewState["SearchStatus"] = ddlSearchStatus.SelectedValue;
        //else
        //    ViewState["SearchStatus"] = null;

        RefreshDataGridView();
    }

    protected void CreateButton_Click(object sender, EventArgs e)
    {
        RefreshDataGridView();
    }

    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        RefreshDataGridView();
    }

    #endregion

    private void RefreshDataGridView()
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }

}
